<template>
  <div class="start-process-page">
    <div class="start-process-header">
      <div class="start-process-header-row">
        <el-button round icon="send" type="primary" :disabled="loading" @click="submit">发送</el-button>
        <el-button round icon="save" @click="save" :disabled="loading">保存待发</el-button>
      </div>

      <el-form class="start-process-header-form" ref="headerForm"
               status-icon label-width="40px" :rules='[]'
               :model="processDefinition">
        <el-form-item prop="title" label="标题">
          <el-input readonly v-model="processDefinition.titleFormula.formulaTitle"/>
        </el-form-item>

        <el-form-item prop="title" label="流程">
          <div class="start-process-header-row-wrapper">
            <el-input style="flex: 1" readonly v-model="flowNodeNames"/>
            <el-button icon="view" style="margin-left: 10px" round @click="openFlowPreviewModal">查看流程</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="start-process-body">
      <div class="start-process-content-wrapper">
        <DefaultFormRender :pageAction="pageAction" :formDefinition="formDefinition" :viewAction="viewAction"
                           ref="DefaultFormRender" :view="view" :components="components"/>
        <FSection title="相关附件" class="start-process-content-section" :style="sectionStyle">
          <FUploader ref="FUploader"/>
        </FSection>

        <FSection title="附言" class="start-process-content-section" :style="sectionStyle">
          <froala id="edit" :tag="'textarea'" placeholder="请输入附言" :config="froalaConfig"
                  v-model:value="formFlowDesc.additionalComments"></froala>
        </FSection>

        <FSection v-show="isNotEmpty(businessId)" title="审批历史"
                  class="start-process-content-section" :style="sectionStyle">
          <FlowHistory :business-id="businessId"/>
        </FSection>
      </div>
    </div>
    <FlowPreviewModal ref="FlowPreviewModal"/>
  </div>
</template>

<script>
import {getAction, postAction} from '@/request/BaseRequest';
import {DefaultFlowDefinition} from '@/components/flow/DefaultFlowDefinition';
import DefaultFormRender from '@/components/platwork/FormDetailComponent/DefaultFormDetailComponent/DefaultFormRender';
import {DefaultViewAction, DefaultViewDefinition} from '@/components/form/DefaultFormDefinition';
import {getViewActionId, isEmpty, isNotEmpty} from '@/utils/CommonUtils';
import './style.css';
import FlowPreviewModal from '@/components/flow/FlowPreviewModal.vue';
import FSection from '@/components/FSection/index.vue';
import FUploader from '@/components/FUploader';
import Down from '@/icons/down.vue';
import {froalaConfig} from '@/components/MyFroala';
import FlowHistory from '@/components/platwork/FlowHistory';

export default {
  name: "StartProcess",
  components: {
    Down,
    FSection,
    DefaultFormRender,
    FlowPreviewModal,
    FlowHistory,
    FUploader
  },
  data() {
    return {
      froalaConfig: {
        ...froalaConfig,
        zIndex: 10,
      },
      processDefinition: DefaultFlowDefinition,
      toggleStatus: false,
      loading: false,
      businessId: undefined,
      formDefinition: {
        form: {},
        formFields: []
      },
      pageAction: 'edit', //edit, detail, approve, add
      viewAction: DefaultViewAction,
      view: JSON.parse(JSON.stringify(DefaultViewDefinition)),
      components: [],
      flowNodeNames: undefined,
      formFlowDesc: {
        attachmentIds: undefined,
        additionalComments: undefined,
        formDefinitionId: undefined,
        formName: undefined,
      }
    };
  },
  mounted() {
    this.pageAction = this.$route.query.action;

    if (this.pageAction === 'add') {
      if (this.hasMenuId()) {
        this.loadMenu().then(() => {
          this.loadProcessDefinition(() => {
            this.loadViewActionIdFormDefinitionPublished().then(() => {
              this.loadAndSetFormData();
            });
          });
        });
      } else {
        if (this.hasFlowId()) {
          this.loadProcessDefinition(() => {
            this.loadViewActionIdFormDefinitionPublished().then(() => {
              this.loadAndSetFormData();
            });
          });
        }
      }
    }

    if (this.pageAction === 'edit') {
      this.loadProcessDefinitionById().then(() => {
        this.loadViewActionIdFormDefinitionPublished().then(() => {
          this.loadAndSetFormData();
        });
      });
    }
  },
  methods: {
    isNotEmpty,
    hasMenuId() {
      return isNotEmpty(this.$route.query.menuId);
    },
    hasFlowId() {
      if (isNotEmpty(this.$route.query.flowId)) {
        this.flowId = this.$route.query.flowId;
        return true;
      }
      return false;
    },
    loadMenu() {
      return new Promise((success, err) => {
        this.loading = true;
        getAction('/plat/platAppMenuPublish/queryById',
          {id: this.$route.query.menuId}).then(data => {
          this.loading = false;
          if (data.success) {
            let result = data.result;
            this.menu = result;
            this.flowId = this.menu.flowId;
            success();
          }
        });
      });
    },
    toggleComments() {
      this.toggleStatus = !this.toggleStatus;
    },
    loadViewActionIdFormDefinitionPublished() {
      return new Promise((success, err) => {
        let viewActionId = getViewActionId(this.processDefinition);
        this.loading = true;
        getAction('/plat/loadviewActionIdFormDefinitionPublished', {viewActionId}).then(data => {
          this.loading = false;
          if (data.success) {
            let result = data.result;
            this.setViewActionIdFormDefinitionPublished(result);
            success();
          }
        });
      });
    },
    setViewActionIdFormDefinitionPublished(result) {
      this.setViewDefinition(result.views[0]);
      this.setViewAction(result.viewAction);
      this.setFormDefinition1(result);
    },
    loadProcessDefinition(callback) {
      this.loading = true;
      getAction('/flow/loadProcessDefinition', {id: this.flowId}).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          this.setProcessDefinition(result);
          callback();
        }
      });
    },
    loadProcessDefinitionById() {
      return new Promise((success, err) => {
        this.loading = true;
        let id = this.$route.query.processDefinitionId;
        if (isEmpty(id)) return;
        getAction('/flow/loadProcessDefinition', {id}).then(data => {
          this.loading = false;
          if (data.success) {
            let result = data.result;
            this.setProcessDefinition(result);
            success();
          }
        });
      });
    },
    setProcessDefinition(processDefinition) {
      this.processDefinition = processDefinition;
      this.parseNodeNames();
    },
    parseNodeNames() {
      this.flowNodeNames = undefined;
      try {
        let flowModel = JSON.parse(this.processDefinition.flowDefinition);
        let nodes = flowModel.nodes;
        if (isEmpty(nodes)) return;
        let names = nodes.map(node => node.name);
        names = names.filter(name => isNotEmpty(name));
        this.flowNodeNames = names.toString();
      } catch (e) {
      }
    },
    setViewAction(viewAction) {
      this.viewAction = viewAction;
    },
    setViewDefinition(data) {
      data.viewDefinition = JSON.parse(data.viewDefinition);
      this.view = data;
      this.components = this.view.viewDefinition.children;
    },
    loadAndSetFormData() {
      if (this.pageAction === 'add') {
        this.loadDefaultValues((defaultValues) => {
        });
      } else if (this.pageAction === 'edit') {
        this.queryFormDataById().then(formData => {
          this.resolvePageAction(formData);
        });
      }
    },
    resolvePageAction(formData) {
      if (formData.flow_status !== '0') {
        this.pageAction = 'static';
      }
    },
    loadDefaultValues(success) {
      this.loading = true;
      getAction("/plat/loadDefaultValuesByViewActionId", {
        viewActionId: this.viewAction.id,
        buttonId: this.$route.query.buttonId,
        relateIds: this.$route.query.relateIds
      }).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          this.$refs.DefaultFormRender.setFormData(result);
        }
      });
    },
    queryFormDataById() {
      return new Promise((success, err) => {
        let id = this.$route.query.businessId;
        let formId = this.processDefinition.formId;
        if (isEmpty(id) || isEmpty(formId)) return;
        this.businessId = id;

        this.loading = true;
        getAction('/plat/loadFormDataById', {id, formId}).then(data => {
          this.loading = false;
          if (data.success) {
            let result = data.result;
            this.setFormData(result);
          }
        });
      });
    },
    setFormData(result) {
      this.formData = result.formData;
      this.formFlowDesc = result.formFlowDesc;
      this.$refs.DefaultFormRender.setFormData(this.formData);
      this.$refs.FUploader.setData(this.formFlowDesc.attachmentIds);
    },
    setFormDefinition1(formDefinition) {
      if (isEmpty(formDefinition)) return;
      this.formDefinition.form = formDefinition;
      this.formDefinition.formFields = formDefinition.fields;
      this.formDefinition.formRelationVos = formDefinition.formRelationVos;

      let tempSubForms = [];
      if (isNotEmpty(formDefinition.subForms)) {
        formDefinition.subForms.forEach(subForm => {
          tempSubForms.push({
            fields: subForm.fields,
            subForm
          });
        });
      }
      this.formDefinition.subForms = tempSubForms;
      this.$refs.DefaultFormRender.setFormDefinition(this.formDefinition);
    },
    createSaveData() {
      let formData = this.$refs.DefaultFormRender.getFormData();
      formData.processDefinitionId = this.processDefinition.id;
      this.formFlowDesc.formName = this.formDefinition.form.formName;
      this.formFlowDesc.formDefinitionId = this.formDefinition.form.id;
      this.formFlowDesc.attachmentIds = this.$refs.FUploader.getAttachmentIds();
      let data = {
        selectedFlow: {
          id: this.processDefinition.id,
          titleFormula: this.processDefinition.titleFormula
        },
        formData,
        formFlowDesc: this.formFlowDesc
      };
      return data;
    },
    createSubmitData() {
      return new Promise((success, err) => {
        this.$refs.DefaultFormRender.getFormDataWithCheck().then(formData => {
          formData.processDefinitionId = this.processDefinition.id;
          this.formFlowDesc.formName = this.formDefinition.form.formName;
          this.formFlowDesc.formDefinitionId = this.formDefinition.form.id;
          this.formFlowDesc.attachmentIds = this.$refs.FUploader.getAttachmentIds();
          let data = {
            formData,
            formFlowDesc: this.formFlowDesc,
            selectedFlow: {
              id: this.processDefinition.id,
              titleFormula: this.processDefinition.titleFormula
            }
          };
          success(data);
        });
      });
    },
    submit() {
      this.createSubmitData().then(data => {
        postAction('/plat/submit', data).then(data => {
          this.loading = false;
          if (data.success) {
            let result = data.result;
            console.log(result);
            this.$windowManager.close();
          }
        });
      });
    },
    save() {
      let data = this.createSaveData();
      this.loading = true;
      postAction('/plat/update', data).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          console.log(result);
          this.$windowManager.close();
        }
      });
    },
    openFlowPreviewModal() {
      this.$refs.FlowPreviewModal.setData({id: this.processDefinition.id});
    },
  },
  computed: {
    sectionStyle() {
      return {
        width: `${this.view.width + 40}px`,
        'min-width': "0"
      };
    },
  }
};
</script>
